<template>
  <el-card class="log-manage-container">
    <div class="header">
      <h2>操作日志</h2>
      <div class="filters">
        <el-input v-model="filterUser" placeholder="操作人" clearable style="width: 150px" />
        <el-select v-model="filterType" placeholder="操作类型" clearable>
          <el-option label="用户管理" value="user" />
          <el-option label="预约管理" value="booking" />
          <el-option label="会议室管理" value="room" />
          <el-option label="系统设置" value="system" />
        </el-select>
        <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        />
        <el-button type="primary" :icon="Search" @click="loadLogs">搜索</el-button>
        <el-button type="success" :icon="Download" @click="exportLogs">导出</el-button>
      </div>
    </div>

    <el-table
        :data="filteredLogs"
        style="width: 100%"
        stripe
        v-loading="loading"
    >
      <el-table-column prop="time" label="操作时间" width="170" sortable />
      <el-table-column prop="user" label="操作人" width="120" />
      <el-table-column prop="type" label="操作类型" width="120">
        <template #default="{ row }">
          <el-tag :type="typeTag[row.type]">
            {{ typeText[row.type] }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="action" label="操作内容" />
      <el-table-column prop="target" label="操作对象" width="150" />
      <el-table-column prop="ip" label="IP地址" width="150" />
    </el-table>

    <div class="pagination">
      <el-pagination
          background
          layout="prev, pager, next, sizes, total"
          :total="totalItems"
          :page-size="pageSize"
          :current-page="currentPage"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
      />
    </div>
  </el-card>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { Search, Download } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import type { LogRecord } from './types'

// 模拟数据生成
const generateLogs = (count = 50): LogRecord[] => {
  const actions = {
    user: ['添加用户', '删除用户', '修改用户信息', '重置用户密码'],
    booking: ['通过预约', '拒绝预约', '取消预约', '修改预约'],
    room: ['添加会议室', '修改会议室', '禁用会议室', '启用会议室'],
    system: ['修改系统设置', '更新权限配置', '备份系统数据', '恢复系统数据']
  }

  const users = ['admin', 'manager1', 'manager2', 'supervisor']
  const ips = ['192.168.1.100', '192.168.1.101', '192.168.1.102', '192.168.1.103']

  const logs: LogRecord[] = []
  const now = new Date()

  for (let i = 0; i < count; i++) {
    const type = Object.keys(actions)[Math.floor(Math.random() * Object.keys(actions).length)] as keyof typeof actions
    const actionList = actions[type]
    const action = actionList[Math.floor(Math.random() * actionList.length)]

    const time = new Date(now.getTime() - Math.floor(Math.random() * 30) * 24 * 60 * 60 * 1000 + Math.floor(Math.random() * 24 * 60 * 60 * 1000))

    logs.push({
      id: i + 1,
      time: time.toLocaleString(),
      user: users[Math.floor(Math.random() * users.length)],
      type: type,
      action: action,
      target: getTargetByAction(type, action),
      ip: ips[Math.floor(Math.random() * ips.length)]
    })
  }

  // 按时间倒序排序
  return logs.sort((a, b) => new Date(b.time).getTime() - new Date(a.time).getTime())
}

// 根据操作类型生成目标对象
const getTargetByAction = (type: string, action: string): string => {
  const targets: Record<string, Record<string, string>> = {
    user: {
      '添加用户': `用户ID: ${Math.floor(100000 + Math.random() * 900000)}`,
      '删除用户': `用户ID: ${Math.floor(100000 + Math.random() * 900000)}`,
      '修改用户信息': `用户ID: ${Math.floor(100000 + Math.random() * 900000)}`,
      '重置用户密码': `用户ID: ${Math.floor(100000 + Math.random() * 900000)}`
    },
    booking: {
      '通过预约': `预约ID: ${Math.floor(1000 + Math.random() * 9000)}`,
      '拒绝预约': `预约ID: ${Math.floor(1000 + Math.random() * 9000)}`,
      '取消预约': `预约ID: ${Math.floor(1000 + Math.random() * 9000)}`,
      '修改预约': `预约ID: ${Math.floor(1000 + Math.random() * 9000)}`
    },
    room: {
      '添加会议室': `A区${Math.floor(100 + Math.random() * 100)}`,
      '修改会议室': `B区${Math.floor(100 + Math.random() * 100)}`,
      '禁用会议室': `C区${Math.floor(100 + Math.random() * 100)}`,
      '启用会议室': `D区${Math.floor(100 + Math.random() * 100)}`
    },
    system: {
      '修改系统设置': '预约规则',
      '更新权限配置': '角色权限',
      '备份系统数据': '数据库备份',
      '恢复系统数据': '数据库恢复'
    }
  }

  return targets[type][action]
}

// 类型定义
const typeText = {
  user: '用户管理',
  booking: '预约管理',
  room: '会议室管理',
  system: '系统设置'
}

const typeTag = {
  user: '',
  booking: 'success',
  room: 'warning',
  system: 'danger'
}

// 数据状态
const allLogs = ref<LogRecord[]>([])
const filteredLogs = ref<LogRecord[]>([])
const loading = ref(true)
const filterUser = ref('')
const filterType = ref('')
const dateRange = ref([])

// 分页参数
const totalItems = ref(0)
const pageSize = ref(10)
const currentPage = ref(1)

// 初始化加载数据
onMounted(() => {
  loadLogs()
})

// 加载日志数据
const loadLogs = () => {
  loading.value = true
  setTimeout(() => {
    allLogs.value = generateLogs(100)
    applyFilters()
    loading.value = false
  }, 800)
}

// 应用筛选条件
const applyFilters = () => {
  let result = [...allLogs.value]

  // 用户筛选
  if (filterUser.value) {
    result = result.filter(log => log.user.includes(filterUser.value))
  }

  // 类型筛选
  if (filterType.value) {
    result = result.filter(log => log.type === filterType.value)
  }

  // 日期筛选
  if (dateRange.value && dateRange.value.length === 2) {
    const [start, end] = dateRange.value
    result = result.filter(log => {
      const logDate = new Date(log.time)
      return logDate >= start && logDate <= end
    })
  }

  totalItems.value = result.length
  updatePageData(result)
}

// 更新分页数据
const updatePageData = (data: LogRecord[]) => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  filteredLogs.value = data.slice(start, end)
}

// 分页事件处理
const handlePageChange = (page: number) => {
  currentPage.value = page
  applyFilters()
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  applyFilters()
}

// 导出日志
const exportLogs = () => {
  ElMessage.success('日志导出功能已触发，实际项目中会下载CSV文件')

  // 在实际项目中，这里会生成CSV文件并提供下载
  // 以下是模拟的导出逻辑：
  const headers = ['操作时间', '操作人', '操作类型', '操作内容', '操作对象', 'IP地址']
  const data = filteredLogs.value.map(log => [
    log.time,
    log.user,
    typeText[log.type],
    log.action,
    log.target,
    log.ip
  ])

}
</script>

<style scoped lang="scss">
.log-manage-container {
  padding: 20px;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    flex-wrap: wrap;
    gap: 15px;

    h2 {
      margin: 0;
      font-size: 24px;
      color: #333;
    }
  }

  .filters {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    align-items: center;
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>